<template>
  <div>
    <el-row>
      <el-col :span="12">
        <cs-cell label="分享功能">
          <el-form :model="shareMenuForm"  ref="ruleForm">
            <el-form-item>
              <el-checkbox-group v-model="shareMenuForm.checkedMenu">
                <el-checkbox v-for="menu in shareMenuList" :label="menu.id" :key="menu.id">{{
                    menu.value
                  }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
        </cs-cell>
      </el-col>
      <el-col :span="12">
        <cs-cell label="账户列表">
          <avue-crud :option="accountOption"
                     :data="accountListData"
                     :table-loading="accountLoading"
                     ref="crudAccount"
                     @on-load="onloadAccount"
                     :row-class-name="getRowClassName"
                     share2advAcctTable
          >
            <template slot="permission" slot-scope="scope">
              <!--              <el-select id="id-business-components-offershaare-accountPermissionChange"-->
              <!--                         :disabled="!(!openCheck && scope.row.id != null)" v-model="scope.row.permission"-->
              <!--                         @change="accountPermissionChange($event,scope.row)">-->
              <!--                <el-option v-for="item in accountPermissionList" :key="item.dictKey*1"-->
              <!--                           :label="item.dictValue" :value="item.dictKey*1">-->
              <!--                </el-option>-->
              <!--              </el-select>-->
              <el-select v-model="scope.row.permission" multiple
                         collapse-tags placeholder="请选择"
                         @change="accountPermissionChange($event,scope.row)"
                         size="mini">
                <el-option
                  v-for="item in permissionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </template>
            <template slot="menuRight">
              <el-link v-if="!openCheck" :disabled="offerInfo === null"
                       type="primary"
                       @click="handleAccountAdd">新增账户
              </el-link>
            </template>
            <template slot="menu" slot-scope="{row}">
              <el-button
                id="id-business-components-offershaare-deleteAccount"
                :disabled="row.id == null"
                type="primary"
                size="mini"
                icon="el-icon-delete"
                @click="deleteAccount(row)"
              >删除
              </el-button>
            </template>
          </avue-crud>
          <!--          确认分享-->
          <!--          <el-button id="id-business-components-offershaare-confirmShare2adv" @click="confirmShare2adv" type="primary" size="mini" v-if="advNotarize">确认分享</el-button>-->
        </cs-cell>
      </el-col>
    </el-row>
    <!--    account新增dialog-->
    <el-dialog :visible.sync="accountAddDialog" :modal-append-to-body="false" width="70%" :append-to-body="true"
               :before-close="accountAddDialogClose">
      <offer-share2adv-account-add ref="idleAccountAdd" :offer-id="offerId"></offer-share2adv-account-add>
      <span slot="footer" class="dialog-footer">
        <el-button id="id-business-components-offershaare-accountAddDialogClose"
                   @click="accountAddDialogClose">取 消</el-button>
        <el-button id="id-business-components-offershaare-submitAccount" type="primary"
                   @click="submitAccount">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import offerShare2advAccountAdd from './offerShare2advAccountAdd'
import {getSysDictList} from '@/api/system/dict'
import {
  getShare2advAccountOuter,
  removeShare2advAccount,
  confirmShare2advAccount,
  updateShare2advAccountPermission
} from '@/api/business/share'
import {getDetail as getAdvDetail} from '@/api/business/customer'
import {getExternalAccount} from "@/api/business/account";
import CsCell from "@/components/CsCell/CsCell";

export default {
  name: 'offerShareAdv',
  components: {
    offerShare2advAccountAdd,
    CsCell
  },
  props: {
    confirmToShare: {
      type: Number
    },
    offerId: {
      type: String
    },
    offerInfo: {
      type: Object
    },
    openCheck: {
      type: String | Boolean
    },
  },
  watch: {
    offerInfo: {
      deep: true,
      handler(val, old) {
        if (val === old) {
          return
        }
        this.loadAdvData();
      }
    },
    offerId: {
      deep: true,
      handler(val, old) {
        if (val === old) {
          return
        }
        getSysDictList("account_offer_permission").then(map => {
          this.accountPermissionList = map['account_offer_permission']
        })
        getExternalAccount(this.offerId).then(res => {
          this.accountData = res.data.data;
          this.updateNewAccountData();
        })
      }
    },
  },
  data() {
    return {
      advNotarize: true,
      advData: [{advName: ''}],
      //账户列表配置
      accountOption: {
        editBtn: false,
        addBtn: false,
        delBtn: false,
        refreshBtn: false,
        columnBtn: false,
        menuWidth: 120,
        menu: true,
        height: 300,
        column: [
          {
            label: '账户名称',
            prop: 'name',
          }, {
            label: '账户ID',
            prop: 'accountId',
          }, {
            label: '权限',
            prop: 'permission',
            slot: true,
          }
        ]
      },
      originAccountListData: [],
      accountListData: [],//账户数据
      accountLoading: false,
      accountPermissionList: [],//账户列表权限
      accountAddDialog: false,//account新增弹窗
      pageAccount: {
        pageSize: 10,
        pageSizes: [10, 30, 50, 100, 200],
        layout: "total,pager,prev,next",
        currentPage: 1,
        total: 0
      },
      accountData: [],
      newAccountData: [],
      // 分享菜单功能表单
      shareMenuForm: {
        checkedMenu: []
      },
      // 分享菜单列表
      shareMenuList: [{id: '1', value: '商务中心-花费报告'}, {id: '2', value: '订单中心-效果报告'}, {id: '3', value: '订单中心-数据报告'}],
      // 分享权限列表
      permissionOptions: [{
        value: '1',
        label: '含花费'
      }, {
        value: '2',
        label: '含点击'
      }, {
        value: '3',
        label: '含曝光'
      }, {
        value: '4',
        label: '含安装'
      }]
    }
  },
  created() {
    if (this.confirmToShare === 1) {
      this.advNotarize = false
      this.accountOption.menu = false
    }
  },
  methods: {
    getDictValue(list, key) {
      if (!key || !list || list.length == 0) {
        return key;
      }
      let val = [];
      let newkeys = key;
      if (!(key instanceof Array)) {
        newkeys = [key];
      }
      newkeys.forEach((item) => {
        if (item) {
          for (let i = 0; i < list.length; i++) {
            if (list[i].dictKey == item) {
              val.push(list[i].dictValue);
              return;
            }
          }
        }
      });
      return newkeys.join(",");
    },
    updateNewAccountData() {
      let newAccountData = [];
      this.accountData.forEach((ele) => {
        let newEle = {
          name: ele.name,
          platform: ele.platform,
          platformId: ele.platformId,
          permission: ((ele.permission == -1) ? null : ele.permission),
        };
        newAccountData.push(newEle);
      });
      this.newAccountData = newAccountData;
      this.updateAccountListData();
    },
    updateAccountListData() {
      this.accountListData = this.newAccountData.concat(this.originAccountListData);
    },
    getRowClassName(item) {
      if (item.row.id == undefined) {
        return "externalAcctClass";
      } else {
        return "";
      }
    },
    loadAdvData() {
      let self = this;
      if (self.offerInfo != null && (self.offerInfo.customerId) && self.offerInfo.customerId != -1) {
        // 获取订单详情
        getAdvDetail(self.offerInfo.customerId).then(res => {
          if (res.data.code === 200) {
            self.advData = [{advName: res.data.data.name}];
            this.$emit('adv-name', self.advData)
          }
        });
        self.onloadAccount(self.pageAccount, {});
      }
    },
    onloadAccount(page, params = {}) {
      let self = this;
      self.accountLoading = true;
      if (!self.offerId) {
        self.accountLoading = false;
        self.pageAccount.total = 0;
        self.originAccountListData = [];
        self.accountData = [];
        self.updateNewAccountData();
        self.updateAccountListData();
        return
      }
      let param = {
        type: 'shareable',
        offerId: self.offerId,
      };
      // debugger
      // console.log('offerId', self.offerId)
      getShare2advAccountOuter(
        page.currentPage,
        page.pageSize,
        // Object.assign(params, param)
         self.offerId
      ).then(res => {
        // console.log('结果', res)
        const data = res.data.data
        self.pageAccount.total = data.total;
        data.records.map(item => {
          // if (item.permission === '') {
          //   item.permission = null;
          // }
          item.permission = item.permission.split(',')
          if (item.permission[0] === '') {
            item.permission = []
          }
        });
        if (data.records && data.records.length > 0) {
          self.shareMenuForm.checkedMenu = data.records[0].dataScope.split(',')
        }
        self.originAccountListData = data.records;
        self.updateAccountListData();
        self.accountLoading = false;
      })
    },
    //修改账户列表权限
    accountPermissionChange(event, row) {
      updateShare2advAccountPermission({
        offerId: this.offerId,
        accountId: row.accountId,
        permission: row.permission.length > 0 ? row.permission.join(',') : ''
      });
    },
    //account列表点击删除
    deleteAccount(row) {
      if (row.id == undefined) {
        return;
      }
      removeShare2advAccount(this.offerId, row.id).then(res => {
        if (res.data.code == 200) {
          this.$message({type: 'success', message: '删除成功'})
          this.onloadAccount(this.pageAccount, {})
        }
      })
    },
    // account新增
    handleAccountAdd() {
      let self = this;
      let excludeIds = [];
      for (let i = 0; i < self.accountListData.length; i++) {
        if (self.accountListData[i].accountId == undefined) {
          continue;
        }
        excludeIds[i] = self.accountListData[i].accountId;
      }
      self.excludeAcctIds = excludeIds;
      self.accountAddDialog = true;
      setTimeout(() => {
        self.$refs.idleAccountAdd.onLoad(self.$refs.idleAccountAdd.page)
      }, 50);
    },
    //账户页面关闭
    accountAddDialogClose() {
      this.accountAddDialog = false
      this.$refs.idleAccountAdd.$refs.crud.searchReset();
    },
    submitAccount() {
      this.$refs.idleAccountAdd.submitAccountAdd()
      this.accountAddDialogClose()
    },
    confirmShare2adv() {
      let self = this;
      // console.log(this.shareMenuForm.checkedMenu)
      confirmShare2advAccount({
        offerId: self.offerId,
        dataScope: this.shareMenuForm.checkedMenu.join(',')
      }).then(res => {
        if (res.data.code == 200) {
          self.$message({type: 'success', message: '保存成功'})
          self.onloadAccount(self.pageAccount, {})
        }
      });
    }
  }
}
</script>
<style scoped>
/deep/ [share2advAcctTable] tr.externalAcctClass {
  background: lightgray;
}
</style>
<!--<style lang="scss" scoped>-->
<!--.avue-crud {-->
<!--  margin-top: -40px;-->
<!--}-->
<!--</style>-->
